#import "PublishActivityUI.h"
#import "IQKeyboardManager.h"
@interface PublishActivityUI ()

@end

@implementation PublishActivityUI
@synthesize theme,weight,address,bdImgPath,serverPath,avatar,reqJobName,desc,activity_time;
@synthesize email,linkman,gender;




-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[IQKeyboardManager sharedManager] setShouldToolbarUsesTextFieldTintColor:YES];
    
}

-(void)backFn{
    [self.navigationController popViewControllerAnimated:NO];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    k=0;
    
    
    
    UILabel* titleLb=[[UILabel alloc] initWithFrame:CGRectMake(100, 0, 120, 44)];
    titleLb.text=@"发布活动";
    titleLb.backgroundColor=[UIColor clearColor];
    titleLb.textAlignment=NSTextAlignmentCenter;
    titleLb.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=titleLb;
    
    int h=[Tools getScreenHeight];
    
    UIButton* cancelBtn= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    [cancelBtn addTarget:self action:@selector(backFn) forControlEvents:UIControlEventTouchUpInside];
    
    CGRect frame_1= CGRectMake(0, 7, 40, 30);
    UIImageView*  backView=[[UIImageView alloc] initWithFrame:frame_1];
    UIImage* image= [UIImage imageNamed:@"newback"];
    backView.image=image;
    [cancelBtn addSubview:backView];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:cancelBtn];
    
    
    UIButton* okBtn= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    [okBtn addTarget:self action:@selector(okFn) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel*  okLb=[[UILabel alloc] initWithFrame:frame_1];
    okLb.text=@"确定";
    okLb.textColor=[UIColor whiteColor];
    [okBtn addSubview:okLb];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:okBtn];
    
    
    
    
    
    table=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, h)];
    table.contentInset=UIEdgeInsetsMake(0, 0, 170, 0);
    table.delegate=self;
    table.dataSource=self;
    table.separatorStyle=NO;
    [self.view addSubview:table];
    
    
}
#pragma mark - table
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==6){
        return 173/2;
    }
    if(indexPath.row==7){
        return 80;
    }
    if(indexPath.row==4){
        return 110;
    }
    if(indexPath.row==5){
        return 80;
    }

    return 55;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 10;
}
-(void)okFn{
    
    
    
    
    NSLog(@"theme==%@",theme);
    if (themeTF.text.length==0) {
        [self.view makeToast:@"请输入主题" duration:1.0 position:@"center"];
        return;
    }
    if (timeTF.text.length==0) {
        [self.view makeToast:@"请输入时间" duration:1.0 position:@"center"];
        return;
        
    }
    if (mpTF.text.length==0) {
        [self.view makeToast:@"请输入电话" duration:1.0 position:@"center"];
        return;
        
    }
    self.address=addrTF.text;
    if (addrTF.text.length==0) {
        [self.view makeToast:@"请输入地址" duration:1.0 position:@"center"];
        return;
        
    }
    
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [[MBProgressHUD showHUDAddedTo:app.window animated:YES] setLabelText:@"处理中,请稍后..."];
    [NSThread detachNewThreadSelector:@selector(doSaveActivityFn) toTarget:self withObject:nil];
    
    
    
    
}
-(void)doSaveActivityFn{
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString*  longi=[ud objectForKey:@"longi"];
    NSString*  lati=[ud objectForKey:@"lati"];
    
    NSString* loginURL=HOST;
    loginURL=[loginURL stringByAppendingString:@"index.php/AppActivity/saveActivity"];
    NSLog(@"保存URL.loginURL==%@",loginURL);
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    [req addPostValue:[NSString stringWithFormat:@"%@",longi] forKey:@"longi"];
    [req addPostValue:[NSString stringWithFormat:@"%@",lati] forKey:@"lati"];
    
    
    [req addPostValue:themeTF.text forKey:@"name"];//主题
    [req addPostValue:descTv.text forKey:@"content"];
    
    self.mp=mpTF.text;
    [req addPostValue:[NSString stringWithFormat:@"%@",self.mp] forKey:@"mp"];
    
    [req addPostValue:[NSString stringWithFormat:@"%@",self.activity_time] forKey:@"activity_time"];//时间
    
    
    [req addPostValue:self.address forKey:@"address"];
    
    NSString* tmpImg=[NSString stringWithFormat:@"%@",self.serverPath];
    tmpImg=[tmpImg stringByAppendingString:@".jpg"];
    NSLog(@"doSaveActivityFn.pic0==%@",pic0);
    [req addPostValue:pic0 forKey:@"photo0"];
    [req addPostValue:pic1 forKey:@"photo1"];
    [req addPostValue:pic2 forKey:@"photo2"];
    [req addPostValue:pic3 forKey:@"photo3"];
    
        
    
    
    
    
    [req startSynchronous];
    NSError *error = [req error];
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        NSDictionary* dic=[response JSONValue];
        code=[[dic objectForKey:@"code"] intValue];
        [self performSelectorOnMainThread:@selector(finishFn) withObject:nil waitUntilDone:YES];
    }
    
}
-(void)finishFn{
    if (code==1) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"reLoadPageFn" object:nil];
        [self.view makeToast:@"发布活动成功" duration:1.0 position:@"center"];
        [self.navigationController popViewControllerAnimated:NO];
        
    }else{
        [self.view makeToast:@"发布活动失败" duration:1.0 position:@"center"];
        
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    if(themeTF==textField){
        NSLog(@"self.textField==%@",textField.text);
        self.theme=textField.text;
    }
    if (timeTF==textField) {
        self.activity_time=textField.text;
    }
    if (mpTF==textField) {
        self.start_addr=textField.text;
    }
    
    if (addrTF==textField) {
        self.address=textField.text;
    }
    
    
    
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    if (descTv==textView) {
        self.desc=textView.text;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:@"TodoViewController"];
    cell.tag = 1;
    if(!cell){
        cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"TodoViewController"];
        
    }else{
        while ([cell.contentView.subviews lastObject] != nil) {
            
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    int row=indexPath.row;
    int y=7;
    
    int px=5;
    if (row==0) {
        
        
        
        
        UILabel  *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(7, 5, 80,46)];
        
        nameLb.text=@"主题";
        nameLb.font=[UIFont systemFontOfSize:14];
        nameLb.textAlignment=NSTextAlignmentLeft;
        nameLb.textColor=[UIColor blackColor];
        nameLb.backgroundColor = [UIColor clearColor];
        [cell.contentView  addSubview:nameLb];
        //
        UIImageView*  bg=[[UIImageView alloc] initWithFrame:CGRectMake(87, 5, 458/2, 50)];
        bg.image=[UIImage imageNamed:@"input2"];
        [cell.contentView  addSubview:bg];
        
        
        themeTF=[[UITextField alloc] initWithFrame:CGRectMake(87+px, 5+2, 458/2-4, 50-4)];
        
        themeTF.delegate=self;
        
        if(self.theme){
            themeTF.text=self.theme;
        }
        [cell.contentView addSubview:themeTF];
    }
    
    if(row==1){
        
        
        UILabel  *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(7.0, 10, 270, 30)];
        
        nameLb.text=@"时间";
        nameLb.font=[UIFont systemFontOfSize:14];
        nameLb.textAlignment=NSTextAlignmentLeft;
        nameLb.textColor=[UIColor blackColor];
        nameLb.backgroundColor = [UIColor clearColor];
        
        [cell.contentView  addSubview:nameLb];
        int y=10;
        
        UIImageView*  bg=[[UIImageView alloc] initWithFrame:CGRectMake(87, 5, 458/2, 50)];
        bg.image=[UIImage imageNamed:@"input2"];
        [cell.contentView  addSubview:bg];
        
        
        timeTF=[[UITextField alloc] initWithFrame:CGRectMake(87+px, 5+2, 458/2-4, 50-4)];
        
        timeTF.delegate=self;
        
        if(theme){
            timeTF.text=self.theme;
        }
        [cell.contentView addSubview:timeTF];
        
        
    }
    if(row==2){
        
        
        UILabel  *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(7.0, 10, 270, 30)];
        
        nameLb.text=@"电话";
        nameLb.font=[UIFont systemFontOfSize:14];
        nameLb.textAlignment=NSTextAlignmentLeft;
        nameLb.textColor=[UIColor blackColor];
        nameLb.backgroundColor = [UIColor clearColor];
        
        [cell.contentView  addSubview:nameLb];
        int y=10;
        
        UIImageView*  bg=[[UIImageView alloc] initWithFrame:CGRectMake(87, 5, 458/2, 50)];
        bg.image=[UIImage imageNamed:@"input2"];
        [cell.contentView  addSubview:bg];
        
        
        mpTF=[[UITextField alloc] initWithFrame:CGRectMake(87+px, 5+2, 458/2-4, 50-4)];
        
        mpTF.delegate=self;
        
        if(self.mp){
            mpTF.text=self.mp;
        }
        [cell.contentView addSubview:mpTF];
        
        
    }

    if(row==3){
        UILabel  *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(7.0, 5, 80, 45)];
        
        nameLb.text=@"地址";
        nameLb.font=[UIFont systemFontOfSize:14];
        nameLb.textAlignment=NSTextAlignmentLeft;
        nameLb.textColor=[UIColor blackColor];
        nameLb.backgroundColor = [UIColor clearColor];
        [cell.contentView  addSubview:nameLb];
        
        
        UIImageView*  bg=[[UIImageView alloc] initWithFrame:CGRectMake(87, 5, 458/2, 50)];
        bg.image=[UIImage imageNamed:@"input2"];
        [cell.contentView  addSubview:bg];
        
        
        
        addrTF=[[UITextField alloc] initWithFrame:CGRectMake(87+px, 5+2, 458/2-4, 50-4)];
       
        
        if (self.address) {
            UILabel* qujianTimeLb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 458/2-4, 50-4)];
            qujianTimeLb.text=[NSString stringWithFormat:@"%@",self.address];
            
            [addrTF addSubview:qujianTimeLb];
        }
        
        [cell.contentView addSubview:addrTF];
        
    }
    if(row==4){
                
        UILabel  *lengthLb = [[UILabel alloc] initWithFrame:CGRectMake(7.0, 5,80, 45)];
        lengthLb.text=@"详情";
        lengthLb.font=[UIFont systemFontOfSize:14];
        lengthLb.textAlignment=NSTextAlignmentLeft;
        lengthLb.textColor=[UIColor blackColor];
        lengthLb.backgroundColor = [UIColor clearColor];
        [cell.contentView  addSubview:lengthLb];
        
        
        UIImageView*  bg=[[UIImageView alloc] initWithFrame:CGRectMake(87, 5, 458/2, 173/2+10)];
        bg.image=[UIImage imageNamed:@"textarea2"];
        [cell.contentView  addSubview:bg];
        
        
        descTv=[[UITextView alloc] initWithFrame:CGRectMake(87+px, 5+2, 458/2-14, 173/2-4+10)];
        descTv.backgroundColor=[UIColor clearColor];
        descTv.delegate=self;
        if (self.desc) {
            descTv.text=self.desc;
        }
        [cell.contentView addSubview:descTv];
        
    }
    
    if(row==5){
        int  x=(320-4*60)/5;
        int w=60;
        addPic1Btn = [[UIButton alloc] initWithFrame:CGRectMake(x, 15, w, w)];
        [addPic1Btn setBackgroundImage:[UIImage imageNamed:@"add_pic"] forState:0];
        [addPic1Btn addTarget:self action:@selector(paiZhao1Fn) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:addPic1Btn];
        //
        addPic2Btn = [[UIButton alloc] initWithFrame:CGRectMake(x*2+w, 15, w, w)];
        [addPic2Btn setBackgroundImage:[UIImage imageNamed:@"add_pic"] forState:0];
        [addPic2Btn addTarget:self action:@selector(paiZhao2Fn) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:addPic2Btn];
        //
        addPic3Btn = [[UIButton alloc] initWithFrame:CGRectMake(x*3+w*2, 15, w, w)];
        [addPic3Btn setBackgroundImage:[UIImage imageNamed:@"add_pic"] forState:0];
        [addPic3Btn addTarget:self action:@selector(paiZhao3Fn) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:addPic3Btn];
        //
        addPic4Btn = [[UIButton alloc] initWithFrame:CGRectMake(x*4+w*3, 15, w, w)];
        [addPic4Btn setBackgroundImage:[UIImage imageNamed:@"add_pic"] forState:0];
        [addPic4Btn addTarget:self action:@selector(paiZhao4Fn) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:addPic4Btn];
        
    }
    if(row==6){
        NSString*  tk=@"1.发布信息请遵守中国的法律,不得发布淫秽,赌博等内容的信息 2.夜店中国不承担因用户违法发布信息所产生的风险.  3.一旦发现用户发布违法信息,夜店中国工作人员将在24小时内予以处理。 ";
        UITextView* tv=[[UITextView alloc] initWithFrame:CGRectMake(10, 5, 300, 80)];
        tv.text=tk;
        tv.textColor=[UIColor grayColor];
        [cell.contentView addSubview:tv];
        
    }
   

       
    
    
    
    
    
    
    
    return cell;
    
}
-(void)paiZhao1Fn{
    k=0;
    [self paiZhaoFn];
}
-(void)paiZhao2Fn{
    k=1;
    [self paiZhaoFn];
}
-(void)paiZhao3Fn{
    k=2;
    [self paiZhaoFn];
}
-(void)paiZhao4Fn{
    k=3;
    [self paiZhaoFn];
}

-(void)paiZhaoFn{
    
    
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
        [chooseImageSheet showInView:self.view];
        
    }else{
        // [[NSNotificationCenter defaultCenter] postNotificationName:@"paidanFn" object:nil];
        
        
        UIActionSheet *chooseImageSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
        [chooseImageSheet showInView:self.view];
    }
    
}
#pragma mark UIActionSheetDelegate Method
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    UIImagePickerController * picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    switch (buttonIndex) {
        case 0://Take picture
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"hideTab" object:nil];
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                
            }else{
                NSLog(@"模拟器无法打开相机");
            }
            [self presentModalViewController:picker animated:YES];
            break;
            
        case 1://From album
            [[NSNotificationCenter defaultCenter] postNotificationName:@"hideTab" object:nil];
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentModalViewController:picker animated:YES];
            break;
            
        default:
            //[self dismissModalViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
            break;
    }
}

#pragma 拍照选择照片协议方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [UIApplication sharedApplication].statusBarHidden = YES;
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        CGSize newSize=CGSizeMake(160, 200);
        image=[self smallImg:image scaledToSize:newSize];
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        NSString* filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
        self.avatar=filePath;
        
        
        //关闭相册界面
        [picker dismissModalViewControllerAnimated:YES];
        
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
        smallimage = [[UIImageView alloc] initWithFrame:
                      CGRectMake(0, 0, 60,60)];
        
        smallimage.image = image;
        
        if(k==0){
            [addPic1Btn addSubview:smallimage];
            
        }
        if(k==1){
            [addPic2Btn addSubview:smallimage];
        }
        if(k==2){
            [addPic3Btn addSubview:smallimage];
        }
        if(k==3){
            [addPic4Btn addSubview:smallimage];
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
        
        [self savePhotoFn];
        
    }
}
-(void)savePhotoFn{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString* uploadURL=@"yw_uploadify.php";
    uploadURL=[HOST stringByAppendingString:uploadURL];
    
    //NSLog(@"uploadURL=%@",uploadURL);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:uploadURL]];
    
    NSDate* now = [NSDate date];
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    
    fmt.dateFormat = @"yyyyMMddHHmmss";
    NSString* dateString = [fmt stringFromDate:now];
    NSLog(@"%@", dateString);
    
    
    self.serverPath=[Tools md5:dateString];
    
    
    
    
    [request setPostValue:self.serverPath forKey:@"serverImgName"];
    
    NSLog(@"%d.....serverPath=%@", k,self.serverPath);
    
    self.serverPath=[self.serverPath stringByAppendingString:@".jpg"];
    if (k==0) {
        pic0=self.serverPath;
    }
    if (k==1) {
        pic1=self.serverPath;
    }
    if (k==2) {
        pic2=self.serverPath;
    }
    if (k==3) {
        pic3=self.serverPath;
    }
    
    [request setFile:self.avatar  forKey:@"filename"];
    
    
    
    
    request.delegate = self;
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [[MBProgressHUD showHUDAddedTo:app.window animated:YES] setLabelText:@"正在处理中，请稍后..."];
    
    
    
    
    [request startAsynchronous];
    
    
    [self savrMyAvatarFn];
}
-(void)savrMyAvatarFn{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //NSString *uid=[userDefaults objectForKey:@"uid"];
    NSString* strFlag=[userDefaults objectForKey:@"flag"];
    int flag=[strFlag intValue];
    
    [self.view makeToast:@"照片保存成功!"
                duration:1.0
                position:[NSValue valueWithCGPoint:CGPointMake(160, 210)]
     ];
    NSDictionary* dic=[NSDictionary dictionaryWithObject:self.avatar forKey:@"avatar"];
    
    
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [MBProgressHUD hideHUDForView:app.window animated:YES];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showTab" object:nil];
    
    
    
    
}

-(UIImage*)smallImg:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
